package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.RecordAdapter;
import com.jsnj33.pdaproject.bean.RecordBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.TimeUtils;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

import static com.jsnj33.pdaproject.utils.TimeUtils.FORMAT_YM2;
import static com.jsnj33.pdaproject.utils.TimeUtils.FORMAT_YMDHMS;

/**
 * @Method： RecordActivity
 * @Author: 萤火虫
 * @Email:allensuns@163.com
 * @Description：数据查询
 */
public class RecordActivity extends AppCompatActivity {
    private static final String TAG = "RecordActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    ImageView iv_back;
    TextView tvStartTime;
    TextView tvEndTime;
    RecyclerView mRecyclerView;
    SmartRefreshLayout SmartRefreshLayout;
    RecordAdapter mRecordAdapter;
    SmartRefreshLayout mSmartRefreshLayout;

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;

    private boolean isScaning = false;
    int page = 1;
    TimePickerView timePicker;
    int type = 0;//0开始时间、1结束时间
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
    String startTime;
    String endTime;
    String usr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initView();
        initChooseTime();
        Listener();
//        quearData("", "", "");
    }

    private void initView() {
        iv_back = findViewById(R.id.iv_back);
        tvStartTime = findViewById(R.id.tvStartTime);
        tvEndTime = findViewById(R.id.tvEndTime);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        mSmartRefreshLayout = findViewById(R.id.mSmartRefreshLayout);
        mRecordAdapter = new RecordAdapter(null);
        mRecyclerView.setAdapter(mRecordAdapter);
    }


    private void Listener() {
        mSmartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                quearData(startTime, endTime, usr);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                quearData(startTime, endTime, usr);
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tvStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = 0;
                if (!timePicker.isShowing()) {
                    try {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date(simpleDateFormat.parse(startTime).getTime()));
                        timePicker.setDate(calendar);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    timePicker.show();
                }
            }
        });
        tvEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = 1;
                if (!timePicker.isShowing()) {
                    try {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date(simpleDateFormat.parse(endTime).getTime()));
                        timePicker.setDate(calendar);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    timePicker.show();
                }
            }
        });
    }

    HashMap hashMap = new HashMap<>();

    /**
     * 查询
     *
     * @param startDate
     * @param endDate
     * @param usr
     */
    private void quearData(String startDate, String endDate, String usr) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Constants.RECORD_LIST;
        Log.d(TAG, "getHttpData-URL: " + url);
        hashMap.put("startDate", startDate);
        hashMap.put("endDate", endDate);
        hashMap.put("usr", usr);
        hashMap.put("pageNo", page);
        hashMap.put("pageSize", 15);
        String params = new Gson().toJson(hashMap);
        Log.d(TAG, "getHttpData:-PARAMS " + params);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d(TAG, "getHttpData-onSuccess: " + jsonObject.toString());
                String status = jsonObject.optString("respCode");
                Boolean nextFlag = jsonObject.optBoolean("nextFlag");
                if (nextFlag) {
                    mSmartRefreshLayout.finishLoadMore();
                    if (page==1) {
                        if (status.equals("-1")) {
                            ToastUtil.showLongToast(RecordActivity.this, "" + jsonObject.optString("respData"));
                        } else {
                            String data = jsonObject.optString("respData");
                            ArrayList<RecordBean> list = new Gson().fromJson(data, new TypeToken<ArrayList<RecordBean>>() {
                            }.getType());
                            mRecordAdapter.setNewData(list);
                        }
                    } else {
                        if (status.equals("-1")) {
                            ToastUtil.showLongToast(RecordActivity.this, "" + jsonObject.optString("respData"));
                        } else {
                            String data = jsonObject.optString("respData");
                            ArrayList<RecordBean> list = new Gson().fromJson(data, new TypeToken<ArrayList<RecordBean>>() {
                            }.getType());
                            mRecordAdapter.addData(list);
                        }
                    }
                } else {
                    mSmartRefreshLayout.finishLoadMoreWithNoMoreData();
                    if (page==1) {
                        if (status.equals("-1")) {
                            ToastUtil.showLongToast(RecordActivity.this, "" + jsonObject.optString("respData"));
                        } else {
                            String data = jsonObject.optString("respData");
                            ArrayList<RecordBean> list = new Gson().fromJson(data, new TypeToken<ArrayList<RecordBean>>() {
                            }.getType());
                            mRecordAdapter.setNewData(list);
                        }
                    } else {
                        if (status.equals("-1")) {
                            ToastUtil.showLongToast(RecordActivity.this, "" + jsonObject.optString("respData"));
                        } else {
                            String data = jsonObject.optString("respData");
                            ArrayList<RecordBean> list = new Gson().fromJson(data, new TypeToken<ArrayList<RecordBean>>() {
                            }.getType());
                            mRecordAdapter.addData(list);
                        }
                    }
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ToastUtil.showGravityToast(RecordActivity.this, "获取失败!", Gravity.CENTER, 0, 0);
                Log.d(TAG, "getHttpData-onFailure: " + error.toString());
            }
        });
        queue.add(jsonObjectRequest);
    }


    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();
        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            Log.i(TAG, "onReceive: " + temp);
            String str = new String(barcode, 0, barcodelen);

            Log.i(TAG, "onReceive: " + str);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(RecordActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);

            Pattern p = Pattern.compile("[a-zA-z]");
            if (sbs.equals("TZ")) {
                ToastUtil.showLongToast(RecordActivity.this, "请扫描工号");
                return;
            } else if (!p.matcher(str).find()) {
                ToastUtil.showLongToast(RecordActivity.this, "请扫描工号");
                return;
            } else {
                /**
                 * 工号
                 */
//                tv_gh_no.setText(str);
                usr = str;
                quearData(startTime, endTime, usr);
                return;
            }
        }

    };


    private void initChooseTime() {
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.setTime(new Date());
        Calendar start = Calendar.getInstance();
        start.set(2020, 0, 1);
        selectedDate.add(Calendar.DATE,1);
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(new Date());
        startTime = TimeUtils.date2Str(startDate.getTime(), TimeUtils.FORMAT_YMD);
        tvStartTime.setText(TimeUtils.date2Str(startDate.getTime(), FORMAT_YM2));
        tvEndTime.setText(TimeUtils.date2Str(selectedDate.getTime(), FORMAT_YM2));
        endTime = TimeUtils.date2Str(selectedDate.getTime(), TimeUtils.FORMAT_YMD);
        timePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (type == 0) {
                    tvStartTime.setText(TimeUtils.date2Str(date, FORMAT_YM2));
                    startTime = TimeUtils.date2Str(date, TimeUtils.FORMAT_YMD);
                } else {
                    tvEndTime.setText(TimeUtils.date2Str(date, FORMAT_YM2));
                    endTime = TimeUtils.date2Str(date, TimeUtils.FORMAT_YMD);
                }
                page = 1;
                quearData(startTime, endTime, usr);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setSubCalSize(15)
                .setTitleSize(18)//标题文字大小
                .setTitleText("时间选择")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(start, selectedDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
    }
}
